//
//  ICOrganizationViewController.m
//  ICome
//
//  Created by zhangrongwu on 16/3/18.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICOrganizationViewController.h"
#import "ICContactTreeCell.h"
#import "ICChatViewController.h"
#import "ICGroup.h"
#import "ICGroupUser.h"
#import "ICSearchViewController.h"
#import "iComeApiManager.h"
@interface ICOrganizationViewController()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate, ICContactTreeCellDelegate, ICSearchViewControllerDelegate>
// 搜索
@property (nonatomic, strong)ICBaseSearchViewController *searchController;
@property (nonatomic, strong)ICSearchViewController *searchVC;
@property (nonatomic, strong)NSIndexPath *currentIndexthPath;
@property (nonatomic, strong)NSMutableArray *dataList;
@property (nonatomic, assign)NSInteger insertRowLevel;
@property (nonatomic, strong)NSString *orgId;

@property (nonatomic, assign)BOOL isFirstRequest;

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIButton *finishButton;

@property (nonatomic, strong)NSString *searchEid; // 搜索记录的人员
@end
@implementation ICOrganizationViewController
#pragma mark - life cycle
-(instancetype)init {
    if (self = [super init]) {
        self.singleSelect = NO;
        self.isFirstRequest = YES;
        self.canCancelSelect = NO;
        self.maxCount = 3000; // 默认值
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setNav];
    [self getData];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45.0f * Level;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ICContactTreeCell";
    ICContactTreeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ICContactTreeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.delegate = self;
        cell.selectedBackgroundView.layer.backgroundColor = TABLECELLSELECTCOLOR.CGColor;
    }
    
    ICEmpInfoModel *model = [self.dataList objectAtIndex:indexPath.row];
    model.kkGroupType = self.kkGroupType;
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self didSelectRowAtIndexPatch:indexPath];
}

#pragma mark - SearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES];
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:ICSEARCHCANCELCOLOR forState:UIControlStateNormal];
        }
    }
}

#pragma mark - CustomDelegate
// 点击选中按钮
- (void)didClickSelectButtonInCell:(ICContactTreeCell *)cell {
   
    if (self.appuserList.count >= self.maxCount) {
        ALERT(@"人数超过上线");
        return;
    }
    self.currentIndexthPath = [self.tableView indexPathForCell:cell];
    ICEmpInfoModel *model = [self.dataList objectAtIndex:self.currentIndexthPath.row];
    if(self.appuserList.count < GROUP_maximum){
        model.select = !model.select;
        BOOL isOId = NO;
        // 判断点击的按钮是否为组织
        if (![ICTools stringEmpty:model.oName]) {
            model.disable = NO;
            isOId = YES;
            for (ICEmpInfoModel *cancel in self.dataList) {
                // 遍历数组、把其他的组织置为cancel
                if (cancel.oId != model.oId && ![ICTools stringEmpty:model.oName]) {
                    if (model.select) {
                        cancel.select = NO;
                    }
                }
            }
        } else {
            
            if (!self.singleSelect) { // 多选
                if (model.select) {
                    [self.recordList addObject:model]; // 每次点击 记录数据
                    [self.appuserList addObject:model]; // 每次点击 记录数据
                } else {
                    [self.recordList enumerateObjectsUsingBlock:^(ICEmpInfoModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj.eId isEqualToString:model.eId]) {
                            [self.recordList removeObject:obj];
                            [self.appuserList removeObject:obj]; // 每次点击 记录数据
                        }
                    }];
                }
                
            } else {
                
                for (ICEmpInfoModel *cancel in self.dataList) {
                    // 遍历数组、 把其他的组置为cancel
                    if (cancel.eId != model.eId) {
                        if (model.select) {
                            cancel.select = NO;
                        }
                    }
                }
                if (model.select) {
                    [self.appuserList addObject:model]; // 每次点击 记录数据
                } else {
                    [self.appuserList removeAllObjects];
                }
            }
            
        }
        NSString *title = @"添加用户";
        if (self.CtrStyle == CtrStyleSelectEmploye_sdk || self.CtrStyle == CtrStyleSelectNode_sdk) {
            title = @"选择";
        }
        if (self.canCancelSelect) {
            title = [NSString stringWithFormat:@"%@(%ld/%lu)", title,self.recordList.count, (self.maxCount - self.users.count)];
        } else {
            title = [NSString stringWithFormat:@"%@(%ld/%lu)", title,(unsigned long)(isOId&&model.select ? model.count : (self.recordList.count - self.users.count)), (self.maxCount - self.users.count)];
        }
        [self.finishButton setTitle:title forState:UIControlStateNormal];
        if (model.select || self.recordList.count != 0) { // 选择的组织或者选择的人员记录不为0
            if (model.count == 0 && (self.kkGroupType == GroupStyleCreateNode || self.kkGroupType == GroupStyleSelectNode)) {
                self.finishButton.highlighted = NO;
                self.finishButton.userInteractionEnabled = NO;
            } else {
                self.finishButton.highlighted = YES;
                self.finishButton.userInteractionEnabled = YES;
            }
        } else {
            self.finishButton.highlighted = NO;
            self.finishButton.userInteractionEnabled = NO;
        }
        
    }else{
        [MBProgressHUD showError:[NSString stringWithFormat:@"每次最多只能向会话中添加%d人",GROUP_maximum]];
    }
    [self.tableView reloadData];
}

// 搜索代理回调
- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath DataSourcmodele:(NSArray *)datasource {
    ICEmpInfoModel *model = [datasource objectAtIndex:indexPath.row];
    if (model.isOrg) {
        [self.dataList removeAllObjects];
        [self getMyDepartmentWithOId:model.oId];
    } else {
        // 搜索出后进入指定的位置
        self.insertRowLevel = 0;
        if (self.CtrStyle == CtrStyleDefault_sdk || self.CtrStyle == CtrStyleDepart_sdk) {
            self.CtrStyle = CtrStyleDepart_sdk;
            NSDictionary *param = @{@"eId":model.eId};
            if ([model.eId rangeOfString:@"bot"].location == NSNotFound) {
                if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsDetailsFromViewC::)]) {
                    [[iComeApiManager instance].delegate openContactsDetailsFromViewC:self:param];
                } else {
                    UIViewController * vc = [[IComMediator sharedInstance] IComMediator_ContactsDetailViewController:param];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else
            {
                UIViewController *vc = [[IComMediator sharedInstance] IComMediator_RobotDetailViewController:param];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        if (self.kkGroupType != GroupStyleCreateNode) {

            if (self.appuserList.count >= self.maxCount) {
                ALERT(@"人数超过上线");
                return;
            }
            
            model.select = YES;
            [self.recordList addObject:model];
            [self.appuserList addObject:model];
            NSString *title = [NSString stringWithFormat:@"%@(%ld/%lu)", @"添加用户",self.recordList.count - self.users.count, (self.maxCount - self.users.count)];
            [self.finishButton setTitle:title forState:UIControlStateNormal];
            self.finishButton.highlighted = YES;
            self.finishButton.userInteractionEnabled = YES;
        }
        
        self.eId = model.eId;
        self.searchEid = model.eId;
        [self.dataList removeAllObjects];
        [self getDataWitheId:self.eId];
    }
    
    // 搜索后状态清空
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

#pragma mark - event response

// 完成按钮
- (void)finishBtnAction {
    WEAKSELF
    if (self.kkGroupType == GroupStyleCreateEmployee) {
        NSDictionary *param = [ICCreateGroupManager createMultGroupParamWithUserList:self.recordList];
        if (!self.isAppendUser) {
            NSArray *eIds = param[@"eIds"];
            if (eIds.count==1 && [eIds.firstObject isEqualToString:[ICUser currentUser].eId]) {
                ALERT(@"无法与自己创建多人群");
                return;
            }
            [ICCreateGroupManager createMultGroupWith:param Handle:^(ICGroup *group) {
                ICChatViewController *vc = [[ICChatViewController alloc] init];
                vc.group = group;
                vc.backFlag = weakSelf.backFlag;
//                [weakSelf pushMyViewController:vc animated:YES index:2];
//                [weakSelf pushToViewController:vc fromViewController:weakSelf animated:YES type:@""];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            
        } else if (self.isAppendUser) {
            // 查询是否是双人组, 双人组则去重新建群
            NSString *gType = [ICMessageDatabase groupTypeWithGroupId:self.gId];
            if ([gType isEqualToString:@"1"]) {  // 双人组
                [self creatNewGroup:self.recordList];
            } else {
                [self appendUser:param[@"eIds"]];
            }
        }
    } else if (self.kkGroupType == GroupStyleCreateNode) { // 创建组织会话
        for (ICEmpInfoModel *model in self.dataList) {
            if (model.select) {
                NSString *gName = model.oName;
                NSString *oId = model.oId;
                NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                                        @"eName":[ICUser currentUser].eName,
                                        @"gName":gName,
                                        @"oId":oId};
                
                [ICCreateGroupManager createOrgGroupWith:param Handle:^(ICGroup *group) {
                    
                    ICChatViewController *vc = [[ICChatViewController alloc] init];
                    vc.group = group;
                    vc.backFlag = weakSelf.backFlag;
//                    [weakSelf pushMyViewController:vc animated:YES index:2];
//                    [weakSelf pushToViewController:vc fromViewController:weakSelf animated:YES type:@""];
                    [self.navigationController pushViewController:vc animated:YES];

                }];
            }
        }
    } else if (self.kkGroupType == GroupStyleSelectNode || self.kkGroupType == GroupStyleSelectEmployee) {
        
        // 轻应选择用户用处理
        if (self.singleSelectionEmp) {
            self.singleSelectionEmp(self.appuserList);
            [self.navigationController popViewControllerAnimated:YES];
        }
        // 用户选择
        if (self.selectionUserList) {
            self.selectionUserList(self.appuserList);
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        // 选择整个组织
        if (self.singleSelectionOrg) {
            NSMutableArray *org = [[NSMutableArray alloc] init];
            for (ICEmpInfoModel *model in self.dataList) {
                if (model.select) {
                    [org addObject:model];
                }
            }
            self.singleSelectionOrg(org);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

// 添加用户
- (void)appendUser:(NSArray *)userList;
{
    NSDictionary *param = @{@"gId":self.gId,
                            @"eIds":userList};
    if ([self.delegate respondsToSelector:@selector(appendUserWithDictionary:)]) {
        [self.delegate appendUserWithDictionary:param];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

// 重新建群
- (void)creatNewGroup:(NSMutableArray *)userList {
    
    [ICMessageDatabase getUsersWithGroupId:self.gId finish:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            for (ICUser *user in array) {
                ICEmpInfoModel *model = [[ICEmpInfoModel alloc] init];
                model.eId = user.eId;
                model.eName = user.eName;
                model.select = YES;
                [userList addObject:model];
            }
        }
    }];
    NSDictionary *param = [ICCreateGroupManager createMultGroupParamWithUserList:userList];
    [ICCreateGroupManager createMultGroupWith:param Handle:^(ICGroup *group) {
        
        ICChatViewController *vc = [[ICChatViewController alloc] init];
        vc.group = group;
        vc.backFlag = @"4";
//        [weakSelf pushMyViewController:vc animated:YES index:2];
//        [weakSelf pushToViewController:vc fromViewController:weakSelf animated:YES type:@""];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}


#pragma mark - private methods
// 设置页面布局
- (void)setUI {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        if (self.CtrStyle == CtrStyleEmploye_sdk || self.CtrStyle == CtrStyleSelectEmploye_sdk || self.CtrStyle == CtrStyleSelectNode_sdk) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-50 - [ICTools getHomebarHeight]);
            self.finishButton.hidden = NO;
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
            self.finishButton.hidden = YES;
        }
    }];
    
    [self.finishButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.equalTo(self.view.mas_left).offset(-10);// 圆角问题
        make.right.equalTo(self.view.mas_right).offset(10);
        make.height.mas_equalTo(50);
//        make.bottom.equalTo(self.view.mas_bottom);
    }];
}
// 设置navigation
- (void)setNav {
    self.title = self.titleName;
}

- (void)setFinishBtnStatus {
    NSString *title = @"添加用户";
    if (self.CtrStyle == CtrStyleSelectEmploye_sdk || self.CtrStyle == CtrStyleSelectNode_sdk) {
        title = @"选择";
    }
    if (self.canCancelSelect) {
        title = [NSString stringWithFormat:@"%@(%ld/%lu)", title,self.recordList.count, (self.maxCount - self.users.count)];
        if (self.recordList.count > 0) {
            self.finishButton.highlighted = YES;
            self.finishButton.userInteractionEnabled = YES;
        } else {
            self.finishButton.userInteractionEnabled = NO;
            self.finishButton.highlighted = NO;
            
        }
    } else {
        title = [NSString stringWithFormat:@"%@(0/%lu)", title,(self.maxCount - self.recordList.count)];
        self.finishButton.userInteractionEnabled = NO;
        self.finishButton.highlighted = NO;
    }
    [self.finishButton setTitle:title forState:UIControlStateNormal];
}

- (void)getData {
    if (self.canCancelSelect) {
        [self getDataWitheId:self.eId];
    } else {
        if (_CtrStyle == CtrStyleDefault_sdk) { // 组织架构
            [self getDataWithOrgId:self.oId];
        } else if (_CtrStyle == CtrStyleDepart_sdk) { // eid 获取部门
            [self getDataWitheId:self.eId];
        } else if (_CtrStyle == CtrStyleEmploye_sdk ||
                   _CtrStyle == CtrStyleSelectEmploye_sdk ||
                   _CtrStyle == CtrStyleSelectNode_sdk) {
            [self getMyDepartmentWithOId:[ICUser currentUser].oId];
        } else {
            [self getMyDepartmentWithOId:self.oId];
        }
    }
    
    // 对与已经选择的用户进行处理
    if (self.isAppendUser) {
        WEAKSELF
        [ICMessageDatabase getUsersWithGroupId:self.gId finish:^(NSArray *array, NSError *error) {
            if (array.count != 0) {
                weakSelf.users = (NSMutableArray *)array;
                for (ICUser *user in weakSelf.users) {
                    ICEmpInfoModel *model = [[ICEmpInfoModel alloc] init];
                    model.eId = user.eId;
                    model.eName = user.eName;
                    model.photoId = user.photoId;
                    model.isExistingUser = YES;
                    [self.recordList addObject:model];
                }
            }
        }];
    }
    
    [self setFinishBtnStatus];
}


-(void)re_getData {
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    [self tableView:self.tableView didSelectRowAtIndexPath:index];
}

- (void)didSelectRowAtIndexPatch:(NSIndexPath *)indexPath {
    ICEmpInfoModel *model = [self.dataList objectAtIndex:indexPath.row];
    self.isFirstRequest = NO;
    if ([ICTools stringEmpty:model.eId]) { // 点击的组织
        self.title = model.oName;
        if (![self.orgId isEqualToString:model.oId]) {
            self.orgId = model.oId;
            for (int index = 0; index < self.dataList.count; index++) {
                ICEmpInfoModel *smodel = self.dataList[index];
                if ([smodel.oId isEqualToString:model.oId]) {
                    smodel.isLastRootNode = YES;
                    smodel.isOpen = YES;
                    [self.dataList removeObjectsInRange:NSMakeRange(index+1, self.dataList.count - (index+1))];
                } else {
                    smodel.isLastRootNode = NO;
                    smodel.isOpen = NO;
                }
            }
            self.insertRowLevel = model.rowLevel+1;
            [self getDataWithOrgId:self.orgId];
        } else {
            self.insertRowLevel = model.rowLevel;
            BOOL loadingUpList = NO; // 进入兼职组时单独处理
            for (int index = 0; index < self.dataList.count; index++) {
                ICEmpInfoModel *pModel = self.dataList[index];
                if ([pModel.oId isEqualToString:model.pId]) { // 为树根节点无法再次找到根节点 所以无法移除数据
                    [self.dataList removeObjectsInRange:NSMakeRange(index+1, self.dataList.count - (index+1))];
                    pModel.isOpen = YES;
                    self.orgId = pModel.oId;
                    [self getDataWithOrgId:pModel.oId];
                    loadingUpList = YES;
                } else {
                    pModel.isOpen = NO;
                }
            }
            if (!loadingUpList) { // 进入兼职组时单独处理
                if (![ICTools stringEmpty:model.pId]) {
                    // 业务需求 进入组织树的根一级
                    [self.dataList removeAllObjects];
                    [self getMyDepartmentWithOId:model.pId];
                } else {
                    return;
                }
            }
        }
    } else {
        if (self.CtrStyle != CtrStyleEmploye_sdk) {
            ICContactTreeCell *cell = (ICContactTreeCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSDictionary *param = @{@"eId":model.eId};
            if ([model.eId rangeOfString:@"bot"].location == NSNotFound) {
                if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsDetailsFromViewC::)]) {
                    [[iComeApiManager instance].delegate openContactsDetailsFromViewC:self:param];
                } else {
                    UIViewController * vc = [[IComMediator sharedInstance] IComMediator_ContactsDetailViewController:param];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else
            {
                UIViewController *vc = [[IComMediator sharedInstance] IComMediator_RobotDetailViewController:param];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        else
        {
            if (!model.isExistingUser && self.kkGroupType != GroupStyleCreateNode) {
                
                ICContactTreeCell *cell = (ICContactTreeCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                [self didClickSelectButtonInCell:cell];
            }
        }
    }
}

// 获取树子节点
- (void)getDataWithOrgId:(NSString *)orgid {
    [MBProgressHUD showLoadingActivityView:self.view];
    NSString *oid = @"";
    if (![ICTools stringEmpty:orgid]) {
        oid = orgid;
    }
    WEAKSELF
    NSDictionary *param = @{@"oId":oid};
    [[ICSocketRequestManager sharedInstance] getSubOrgAndSubEmpListWithObject:param Success:^(id object) {
        NSDictionary *dict = [object objectForKey:@"data"];
        [self reloadTableViewWithData:dict];
        NSArray *orgList = [dict objectForKey:@"orgList"];
        //  业务需求 首次orglist.count 为1时重新获取数据
        if (orgList.count == 1) {
            //#warning 存在一个bug
            if (self.isFirstRequest) {
                [self re_getData];
                return;
            }
        }
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
    }];
}

// eid获取所在部门
- (void)getDataWitheId:(NSString *)eid {
    NSString *empId = @"";
    if (![ICTools stringEmpty:eid]) {
        empId = eid;
    }
    NSDictionary *param = @{@"eId":empId,
                            @"pageNo":@"1",
                            @"pageSize":@"100"};
    [MBProgressHUD showLoadingActivityView:self.view];
    WEAKSELF
    [[ICSocketRequestManager sharedInstance] getOrgsByeIdWithObject:param Success:^(id object) {
        NSDictionary *dict = [object objectForKey:@"data"];
        [self reloadTableViewWithData:dict];
        [MBProgressHUD hideLoadingActivityView:weakSelf.view];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD showError:error.domain];
        [MBProgressHUD hideLoadingActivityView:weakSelf.view];
    }];
}

- (void)getMyDepartmentWithOId:(NSString *)oId {
    NSDictionary *param = @{@"oId":oId};
    [MBProgressHUD showLoadingActivityView:self.view];
    WEAKSELF
    [[ICSocketRequestManager sharedInstance] getOrgsByoIdWithObject:param Success:^(id object) {
        NSDictionary *dict = [object objectForKey:@"data"];
        [self reloadTableViewWithData:dict];
        [MBProgressHUD hideLoadingActivityView:weakSelf.view];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD showError:error.domain];
        [MBProgressHUD hideLoadingActivityView:weakSelf.view];
    }];
}

- (void)reloadTableViewWithData:(NSDictionary *)dict {
    NSArray *employeeList = [dict objectForKey:@"employeeList"];
    NSArray *orgList = [dict objectForKey:@"orgList"];
    NSArray *upOrgList = [dict objectForKey:@"upOrgList"];
    
    __block NSInteger lastIndex = 0;
    // 处理员工上层组织
    for (int i = 0; i < upOrgList.count; i++) {
        NSDictionary *uporgdict = [upOrgList objectAtIndex:i];
        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] initWithDict:uporgdict];
        model.isUser = NO;
        model.rowLevel = i;
        model.CtrStyle = self.CtrStyle;
        if (self.kkGroupType != GroupStyleCreateNode && self.kkGroupType != GroupStyleSelectNode) {
            model.disable = YES;
        }
        if (model.count > self.maxCount) {
            model.disable = YES;
        }
        self.insertRowLevel = upOrgList.count;
        if (i == upOrgList.count - 1) { // 最后一层父节点状态
            model.isLastRootNode = YES;
            model.isOpen = YES;
            self.oId = model.oId;
            self.title = model.oName;
            lastIndex = i;
        }
        [self.dataList addObject:model];
    }
    
    //  处理员工显示状态
    
    [employeeList enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] initWithDict:obj];
        model.isUser = YES;
        model.rowLevel = self.insertRowLevel;
        model.CtrStyle = self.CtrStyle;
        if (self.kkGroupType == GroupStyleCreateNode || self.kkGroupType == GroupStyleSelectNode) {
            model.disable = YES;
        }
        for (ICEmpInfoModel *record in self.recordList) { // 处理记录数据
            if ([model.eId isEqualToString:record.eId]) {
                model.select = YES;
                model.isExistingUser = record.isExistingUser;
            }
        }
        [self.dataList addObject:model];
        
        // 控制选中位置
        if ([model.eId isEqualToString:self.searchEid]) {
            lastIndex = lastIndex+idx + 1;
            self.searchEid = @"";
        }
    }];
    
    // 处理员工下层组织
    for (NSDictionary *orgdict in orgList) {
        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] initWithDict:orgdict];
        model.isUser = NO;
        model.rowLevel = self.insertRowLevel;
        model.CtrStyle = self.CtrStyle;
        if (self.kkGroupType != GroupStyleCreateNode && self.kkGroupType != GroupStyleSelectNode) {
            model.disable = YES;
        }
        if (model.count > self.maxCount) {
            model.disable = YES;
        }
        [self.dataList addObject:model];
    }
    
    [self.tableView reloadData];
    if (lastIndex != 0 && lastIndex < self.dataList.count) {
        [self.tableView scrollToRow:lastIndex inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}


#pragma mark - getters and setters
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.userInteractionEnabled = YES;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
        self.tableView.tableHeaderView = self.searchController.searchBar;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (ICBaseSearchViewController *) searchController {
    if (!_searchController) {
        
        _searchController = [[ICBaseSearchViewController alloc] initWithSearchResultsController:self.searchVC];
        _searchController.placeholder = @"搜索";
        _searchController.searchBar.delegate  = self;
        _searchController.searchResultsUpdater = self.searchVC;
        // 覆盖视图控制器的视图窗口的部分决定了呈现视图控制器的视图的大小。默认值是NO。
        self.definesPresentationContext = YES;
    }
    return _searchController;
}

- (ICSearchViewController *) searchVC {
    if (!_searchVC) {
        _searchVC = [[ICSearchViewController alloc] init];
        _searchVC.delegate = self;
    }
    return _searchVC;
}
- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [[NSMutableArray alloc] init];
    }
    return _dataList;
}
- (NSMutableArray *)recordList {
    if (!_recordList) {
        _recordList = [[NSMutableArray alloc] init];
    }
    return _recordList;
}
-(NSMutableArray *)appuserList {
    if (!_appuserList) {
        _appuserList = [[NSMutableArray alloc] init];
    }
    return _appuserList;
}

-(NSMutableArray *)users {
    if (!_users) {
        _users = [[NSMutableArray alloc] init];
    }
    return _users;
}

- (UIButton *)finishButton {
    if (!_finishButton) {
        _finishButton = [[UIButton alloc] init];
        [_finishButton addTarget:self action:@selector(finishBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _finishButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.view addSubview:_finishButton];
        [_finishButton setBackgroundColor:[UIColor lightGrayColor]];
        [self setFinishBtnStatus];
        _finishButton.userInteractionEnabled = NO;
        [_finishButton setBackgroundImage:[UIImage imageWithColor:NE_BACKGROUND_COLOR] forState:UIControlStateHighlighted];
    }
    return _finishButton;
}

@end
